import {defineStore} from 'pinia'
import {ref, computed} from "vue";

export const useCartStore = defineStore('cart', () => {
  // 1、定义数据  state
  const cartList = ref([])
  const isAll = computed(() => {
    return cartList.value.every(item => item.selected)
  })
  // 2、定义方法  actions
  const addCart = (product) => {
    // cartList.value.push(product)
    const item = cartList.value.find((item) => product.skuId === item.skuId)
    if (item) {
      item.count++;
    } else {
      cartList.value.push(product)
    }
  }

  const delCart = (skuId) => {
    cartList.value = cartList.value.filter(item => item.skuId !== skuId)
  }

  const allCount = computed(() => {
    return cartList.value.reduce((total, item) => total + item.count, 0);
  })

  const allPrice = computed(() => {
    return cartList.value.reduce((total, item) => total + item.price*item.count, 0).toFixed(2);
  })

  const singleCheck = (skuId, selected)=>{
    // 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = selected
  }
  // 全选功能action
  const allCheck = (selected) => {
    // 把cartList中的每一项的selected都设置为当前的全选框状态
    cartList.value.forEach(item => item.selected = selected)
  }

  return {
    cartList,
    allPrice,
    allCount,
    isAll,
    addCart,
    delCart,
    singleCheck,
    allCheck

  }
}, {
  persist: true,
})
